<script setup lang="ts">
import { ref, computed } from 'vue'
import { onPageScroll, onLoad, onReachBottom } from '@dcloudio/uni-app'
import { getCategoryList } from '@/api/category'
import { getGoodsList } from '@/api/goods'
import type { Goods, GoodsReq } from '@/api/goods/type'
import type { Category } from '@/api/category/type'
import type { BaseResponse, ResultType } from '@/api/base'
import { toast } from '@/utils/common'
import { dropdownMenuList, imageStyle } from './common'

const dropDownRef = ref()
const categoryList = ref<Category[]>([])
const goodsList = ref<Goods[]>([])
const goodsReq = ref<GoodsReq>({
  name: null,
  categoryId: null,
  orderBy: null,
  pageNum: 1,
  pageSize: 10
})
const loadStatus = ref<string>('loadmore')
const moreStatus = ref<boolean>(true)

// 加载分类列表
const loadCategoryList = async () => {
  const res: BaseResponse = await getCategoryList()
  categoryList.value = res.data
  const temp: ResultType[] = [{
    label: '全部',
    value: null
  }]
  res.data.forEach((item: Category) => {
    temp.push({
      label: item.name,
      value: item.id
    })
  })
  dropdownMenuList[1].options = temp
}

// 加载商品列表
const loadGoodsList = async () => {
  loadStatus.value = 'loading'
  try {
    const res: BaseResponse = await getGoodsList(goodsReq.value)
    if (goodsReq.value.pageNum == 1 && res.data.records.length < goodsReq.value.pageSize) {
      loadStatus.value = 'nomore'
      moreStatus.value = false
      goodsList.value = goodsList.value.concat(res.data.records)
      goodsReq.value.total = res.data.total
      return
    }
    if (!res.data || res.data.records.length == 0 || res.data.total < goodsList.value.length) {
      loadStatus.value = 'nomore'
      moreStatus.value = false
      return
    }
    goodsList.value = goodsList.value.concat(res.data.records)
    loadStatus.value = 'loadmore'
    goodsReq.value.pageNum++
  } catch (error: BaseResponse) {
    loadStatus.value = 'nomore'
    moreStatus.value = false
    toast(error.tips)
  }
}

onLoad(async () => {
  await loadCategoryList()
  await loadGoodsList()
})

onPageScroll(() => {
  dropDownRef.value.init()
})

onReachBottom(() => {
  // 如果依然还有数据，就触发
  if (moreStatus.value == true) {
    loadStatus.value = 'loading'
    setTimeout(() => {
      loadGoodsList()
      loadStatus.value = 'loadmore'
    }, 500)
  }
})

const handleOpen = () => {
  if (!dropdownMenuList[1].value) {
    dropdownMenuList[1].value = null
  }
  if (!dropdownMenuList[2].value) {
    dropdownMenuList[2].value = null
  }
}
const handleConfirm = (e: any) => {
  const keyArr = Object.keys(e)
  if (keyArr.length == 0) {
    return
  }
  const key = keyArr[0]
  goodsReq.value[key] = e[key]
  resetFilter()
}
const resetFilter = () => {
  goodsReq.value.pageNum = 1
  goodsList.value = []
  loadGoodsList()
}
const loadTabExpress = async () => {
  loadGoodsList()
}
const jumpToOrder = (item: Goods) => {
  uni.navigateTo({
    url: `/pages/goods/detail?id=${item.id}`
  })
}
const publish = () => {
  uni.navigateTo({
    url: '/pages/goods/create'
  })
}

</script>

<template>
  <view class="goods">
    <view class="goods-search">
      <da-dropdown :dropdownMenu="dropdownMenuList" :duration="300" fixedTop @open="handleOpen"
        @confirm="handleConfirm">
      </da-dropdown>
    </view>
    <view class="goods-list" v-if="goodsList && goodsList.length > 0">
      <view class="goods-list-item" v-for="(item) in goodsList" @click="jumpToOrder(item)">
        <view class="goods-list-item-image">
          <my-image :src="item.url.split(',')[0]" mode="aspectFit" :customStyle="imageStyle"></my-image>
        </view>
        <view class="goods-list-item-info">
          <view class="goods-list-item-info-name">
            <uv-text :lines="2" :text="item.name" size='28rpx'></uv-text>
          </view>
          <view class="goods-list-item-info-price">
            <view class="goods-list-item-info-price-num">{{ item.price }}</view>
            <view class="goods-list-item-info-price-unit">元</view>
          </view>
        </view>
      </view>
      <view style="background-color: #fff;">
        <uv-load-more bgColor="#fff" :status="loadStatus" @loadmore="loadTabExpress"></uv-load-more>
      </view>
    </view>
    <uv-empty class="goods-empty" v-else text="没有商品哦~" icon="../../static/empty.png" width="80" height="80"></uv-empty>
    <view class="publish">
      <uv-avatar icon="plus" size="100rpx" fontSize="52rpx" bg-color="#409eff" color="#fff"
        @click="publish"></uv-avatar>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.goods-list {
  display: flex;
  background-color: #fff;
  flex-direction: column;

  .goods-list-item {
    display: flex;
    flex-direction: row;
    padding: 20rpx;
    border-bottom: 1px solid #f1f1f1;

    .goods-list-item-image {
      margin-right: 20rpx;
    }

    .goods-list-item-info {
      flex: 1;
      display: flex;
      justify-content: space-between;
      flex-direction: column;

      .goods-list-item-info-name {
        margin-bottom: 10rpx;
      }

      .goods-list-item-info-price {
        display: flex;
        flex-direction: row;
        align-items: center;

        .goods-list-item-info-price-num {
          color: #ff7744;
          margin-right: 10rpx;
        }

        .goods-list-item-info-price-unit {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .goods-list-item-btn {
      display: flex;
      justify-content: center;
      align-items: end;
      width: 150rpx;
    }
  }
}

.goods-empty {
  background-color: #f1f1f1;
  margin-top: 70% !important;
}

.publish {
  position: fixed;
  bottom: 100rpx;
  right: 30rpx;
}
</style>
